package org.bot.socket.auth;

import java.io.File;
import java.io.IOException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.UUID;

public class MainNetworkInterfaceMAC {


    public static String getMainNetworkInterfaceMac2() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();

                // 排除回环接口和虚拟接口
                if (networkInterface.isLoopback() || networkInterface.isVirtual()) {
                    continue;
                }

                // 获取网卡的硬件地址（MAC 地址）
                byte[] mac = networkInterface.getHardwareAddress();
                if (mac != null) {
                    // 将 MAC 地址转换为十六进制字符串
                    StringBuilder sb = new StringBuilder();
                    for (byte b : mac) {
                        sb.append(String.format("%02x", b));
                    }
                    return sb.toString();
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getMainNetworkInterfaceMac() {
        String jdkPath = System.getProperty("java.home");
        String filePath = jdkPath + File.separator + "bot-cer" + File.separator + "bot-cer.uuid";

        File file = new File(filePath);
        if (file.exists()) {
            try {
                // 读取文件内容并返回
                byte[] bytes = Files.readAllBytes(file.toPath());
                return new String(bytes, StandardCharsets.UTF_8);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                // 创建 bot-cer 文件夹
                Path directoryPath = Paths.get(jdkPath, "bot-cer");
                Files.createDirectories(directoryPath);

                // 生成随机 UUID 并写入文件
                String uuid = UUID.randomUUID().toString();
                Path uuidFilePath = Paths.get(directoryPath.toString(), "bot-cer.uuid");
                Files.write(uuidFilePath, uuid.getBytes(StandardCharsets.UTF_8));
                return uuid;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
